import React, { Component } from "react";

import { Spring } from "react-spring/renderprops";
// 导入三个子组件
import FilterTitle from "../FilterTitle";
import FilterPicker from "../FilterPicker";
import FilterMore from "../FilterMore";

import styles from "./index.module.css";

import { getCurrentCity, API } from "../../../../utils";

export default class Filter extends Component {
  state = {
    titleSelectedStatus: {
      area: false,
      mode: false,
      price: false,
      more: false
    },
    // 控制选择框的显示和隐藏
    openType: "",

    houseCoditions: {
      // FilterMore
      roomType: [],
      oriented: [],
      floor: [],
      characteristic: [],
      // FilterPicker
      area: {},
      subway: {},
      rentType: [],
      price: []
    },

    // 所有筛选条件的选中值
    selectedValues: {
      area: ["area", "null"],
      mode: ["null"],
      price: ["null"],
      more: []
    }
  };

  //  获取 筛选条件的数据
  componentDidMount() {
    // 在进入该组件时，在该钩子函数中获取 body DOM对象
    this.htmlBody = document.body;
    this.getHouseCoditions();
  }
  async getHouseCoditions() {    
    const { value } = await getCurrentCity();
    const res = await API.get("/houses/condition", {
      params: {
        id: value
      }
    });
    this.setState({
      houseCoditions: res.data.body
    });
  }

  // 检查菜单是否选中
  // 传入 当前菜单的类型 和 当前菜单的选中值，最终，返回当前菜单要不要选中
  checkTitleSelected(type, selected) {
    let isChecked = false;
    if (type === "area" && (selected.length === 3 || selected[0] !== "area")) {
      isChecked = true;
    } else if (type === "mode" && selected[0] !== "null") {
      isChecked = true;
    } else if (type === "price" && selected[0] !== "null") {
      isChecked = true;
    } else if (type === "more" && selected.length > 0) {
      // 第四个菜单: 筛选（ 等到该组件功能实现后，再补充 ）
      isChecked = true;
    } else {
      // 不选中
      isChecked = false;
    }

    return isChecked;
  }

  onTitleClick = type => {
    // 展示对话框，并给 body 添加样式，让整个页面内容超出隐藏
    this.htmlBody.classList.add("fixed");
    const { titleSelectedStatus, selectedValues } = this.state;
    const newTitleSelectedStatus = { ...titleSelectedStatus };
    Object.keys(newTitleSelectedStatus).forEach(key => {
      if (key === type) {
        newTitleSelectedStatus[key] = true;
      } else {
        const selected = selectedValues[key];

        const isChecked = this.checkTitleSelected(key, selected);
        newTitleSelectedStatus[key] = isChecked;
      }

      this.setState({
        titleSelectedStatus: newTitleSelectedStatus,
        // 控制对话框的显示与隐藏
        openType: type
      });
    });
  };

  // 点击取消关闭选择框
  onClose = () => {
    // 取消 body 的样式
    this.htmlBody.classList.remove("fixed");
    const { openType, selectedValues, titleSelectedStatus } = this.state;
    const newTitleSelectedStatus = { ...titleSelectedStatus };

    const selected = selectedValues[openType];
    const isChecked = this.checkTitleSelected(openType, selected);

    newTitleSelectedStatus[openType] = isChecked;

    this.setState({
      openType: "",
      titleSelectedStatus: newTitleSelectedStatus
    });
  };

  // 点击确认按钮
  onSave = value => {
    // 取消 body 的样式
    this.htmlBody.classList.remove("fixed");
    const { openType, selectedValues, titleSelectedStatus } = this.state;
    //  获取当前菜单的选中状态
    const isChecked = this.checkTitleSelected(openType, value);

    // 更新当前的菜单的选中状态
    const newTitleSelectedStatus = {
      ...titleSelectedStatus,
      [openType]: isChecked
    };

    // 更新选中状态对象
    const newSelectedValues = {
      ...selectedValues,
      [openType]: value
    };

    // 组装所有的筛选条件数据，然后，传递个 父组件(HouseList 组件)
    const filters = {};
    // 对与 区域 数据来说，需要分别获取  key 和 value
    const areaData = newSelectedValues.area;
    const key = newSelectedValues.area[0];
    let areaValue;
    if (areaData.length === 3) {
      areaValue = areaData[2] === "null" ? areaData[1] : areaData[2];
    } else if (areaData.length === 2) {
      areaValue = "null";
    }
    filters[key] = areaValue;

    // 方式
    filters.rentType = newSelectedValues.mode[0];
    // 租金
    filters.price = newSelectedValues.price[0];
    // 筛选
    filters.more = newSelectedValues.more.join(",");

    // 传递给父组件
    this.props.onFilter(filters);

    this.setState({
      openType: "",
      selectedValues: newSelectedValues,
      titleSelectedStatus: newTitleSelectedStatus
    });
  };

  // 渲染FilterPicker组件
  renderFilterPicker() {
    const {
      openType,
      houseCoditions: { area, subway, rentType, price },
      // 所有筛选条件的选中值
      selectedValues
    } = this.state;

    if (openType !== "area" && openType !== "mode" && openType !== "price")
      return null;
    let data,
      cols = 1,
      defaultValue = selectedValues[openType];

    switch (openType) {
      case "area":
        data = [area, subway];
        cols = 3;
        break;
      case "mode":
        data = rentType;
        break;
      case "price":
        data = price;
        break;
      default:
        // 如果不符合预期的情况下，就可以通过 throw 来手动抛出异常
        throw new Error("Invalid type, expected [area, mode, price]~");
    }

    // console.log(data, cols, defaultValue);

    return (
      <FilterPicker
        onClose={this.onClose}
        onSave={this.onSave}
        openType={this.state.openType}
        data={data}
        cols={cols}
        defaultValue={defaultValue}
        key={openType}
      />
    );
  }

  // 渲染 FilterMore
  renderFilterMore() {
    const {
      openType,
      houseCoditions: { roomType, oriented, floor, characteristic },
      selectedValues
    } = this.state;

    // if (openType !== "more") return null;

    // 数据
    const data = {
      roomType,
      oriented,
      floor,
      characteristic
    };
    // console.log(this.state.houseCoditions);
 
    // 默认选中值
    const defaultValues = selectedValues.more;

    return (
      <FilterMore
        onClose={this.onClose}
        onSave={this.onSave}
        data={data}
        defaultValues={defaultValues}
        type={openType}
      />
    );
  }

  renderMask() {
    const { openType } = this.state;
    const isShow =
      openType === "area" || openType === "mode" || openType === "price";

    return (
      <Spring to={{ opacity: isShow ? 1 : 0 }}>
        {props => {
          // console.log(props);
          if (props.opacity === 0) return null;
          return (
            <div style={props} className={styles.mask} onClick={this.onClose} />
          );
        }}
      </Spring>
    );
  }

  render() {
    const { titleSelectedStatus } = this.state;
    return (
      <div className={styles.root}>
        {/* 前三个菜单的遮罩层 */}
        {/* <div className={styles.mask} /> */}
        {/* {openType === "area" || openType === "mode" || openType === "price" ? (
          <div className={styles.mask} onClick={this.onClose} />
        ) : null} */}

        {this.renderMask()}

        <div className={styles.content}>
          {/* 标题栏 */}
          <FilterTitle
            selected={titleSelectedStatus}
            onClick={this.onTitleClick}
          />

          {/* 前三个菜单对应的内容： */}

          {this.renderFilterPicker()}

          {/* 最后一个菜单对应的内容： */}
          {/* <FilterMore /> */}
          {this.renderFilterMore()}
        </div>
      </div>
    );
  }
}
